pub mod tls_server;
pub mod http_api;
pub mod registry;
pub mod pulsar_bus;

use crate::common::{config::ServerConfig, errors::Result};
use crate::common::storage::{self, Storage};
use crate::common::storage::postgresql::PostgreSQLStorage;
use tracing::{info, error};
use std::sync::Arc;
use crate::common::metrics::METRICS;

pub async fn run(port: u16, config_path: String) -> Result<()> {
    // 加载配置
    let config = crate::common::config::load_server_config(&config_path)?;
    
    info!("Server configuration loaded successfully");
    
    // 初始化存储（PostgreSQL / Redis 可扩展）
    let storage: Arc<dyn Storage> = Arc::new(PostgreSQLStorage::new(&config.database.url).await
        .map_err(|e| crate::common::errors::ManagerError::DatabaseError(e.to_string()))?);

    // 初始化 Pulsar
    let bus = Arc::new(pulsar_bus::PulsarBus::new(&config.pulsar).await
        .map_err(|e| crate::common::errors::ManagerError::QueueError(e.to_string()))?);

    // 启动HTTP API服务器
    let http_storage = storage.clone();
    let http_bus = bus.clone();
    let mut http_cfg = config.clone();
    // 如果 CLI 传入了端口，则仅覆盖 HTTP 端口，TLS 端口保持配置文件
    if port != 0 { http_cfg.server.http_port = port; }
    let http_handle = tokio::spawn(async move { http_api::start_http_server(http_cfg, http_storage, http_bus).await });
    
    // 启动TLS服务器
    let tls_storage = storage.clone();
    let tls_cfg = config.clone();
    let tls_handle = tokio::spawn(async move { tls_server::start_tls_server(tls_cfg, tls_storage).await });
    
    // 初始化基础指标
    METRICS.update_node_metrics(0, 0);
    info!("Server started on port {}", port);
    
    // 等待所有任务完成
    tokio::try_join!(http_handle, tls_handle)?;
    
    Ok(())
} 